﻿Imports OpenTK.Graphics.OpenGL
''' <summary>
''' Formulario Principal
''' </summary>
''' <remarks></remarks>
Public Class frmPrincipal

    Public blnCargado As Boolean = False
    Public objEscenario As Escenario
    Public Shared objBloqueo As Object
    Public Shared objDatosMapa As DatosMapa
    Public Shared strFuncion As String
    Public Shared strMapaRetorno As String
    Public Shared objLocalizacion As Coordenada
    Public Shared objrenderizado As Boolean


    ''' <summary>
    ''' Evento al iniciar la ventana de mapas OPENGL
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub glcPantalla_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles glcPantalla.Load
        objBloqueo = New Object
        blnCargado = True
        objDatosMapa = Nothing
        objLocalizacion = Nothing
        objrenderizado = False
        strMapaRetorno = ""
    End Sub

    ''' <summary>
    ''' Evento al ejecutar el sistema
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub frmPrincipal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        objEscenario = New Escenario(glcPantalla)
        objEscenario.objLocalizacion = New Coordenada(0.0F, 0.0F, 10)
        FuenteStroke.inicializarTextos()
    End Sub

    ''' <summary>
    ''' Evento para manejar la opcione del menu select
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tspSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspSelect.Click
        tspSelect.Checked = True
        tspMover.Checked = False
        tspZoom.Checked = False
        tspInfo.Checked = False
    End Sub

    ''' <summary>
    ''' Evento para manejar la opcione del menu mover
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tspMover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspMover.Click
        tspSelect.Checked = False
        tspMover.Checked = True
        tspInfo.Checked = False
        tspZoom.Checked = False
    End Sub

    ''' <summary>
    ''' Evento para manejar la opcione del menu zoom
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tspZoom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspZoom.Click
        tspSelect.Checked = False
        tspMover.Checked = False
        tspInfo.Checked = False
        tspZoom.Checked = True
    End Sub

    ''' <summary>
    ''' Evento para manejar la opcione del menu info
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tspInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspInfo.Click
        tspSelect.Checked = False
        tspMover.Checked = False
        tspZoom.Checked = False
        tspInfo.Checked = True
    End Sub

    Dim intMouseY As Single = 10
    Dim intMouseX As Single = 10
    Dim intZoom As Single = 100

    ''' <summary>
    ''' Evento para manejar la opciones del menu que requieren de analisis de movimiento del mouse
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub glcPantalla_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles glcPantalla.MouseMove
        Dim objCoor As Coordenada = objEscenario.coordenadasXY(e.X, e.Y)
        Me.Text = "Valor en X: " & objCoor.X
        Me.Text &= " Valor en Y: " & objCoor.Y * -1
        Me.Text &= " LocalizacionX: " & objEscenario.objLocalizacion.X
        Me.Text &= " LocalizacionY: " & objEscenario.objLocalizacion.Y * -1
        Me.Text &= " Zoom: " & objEscenario.objLocalizacion.Z
        'JS: Paneo
        If (tspMover.Checked AndAlso blnMouse) Then
            Dim xtmpcoord As Single
            Dim ytmpcoord As Single
            xtmpcoord = (intMouseX - e.X) * 1.5
            ytmpcoord = (intMouseY - e.Y) * 1.5
            xtmpcoord += (glcPantalla.Width / 2)
            ytmpcoord += (glcPantalla.Height / 2)
            objEscenario.Localizacion = objEscenario.coordenadasXY(xtmpcoord, ytmpcoord)
        End If
        'JS: Zoom
        If (tspZoom.Checked AndAlso blnMouse) Then
            intZoom += (intMouseY - e.Y) * (-10 * (intZoom / 350))
            If (intZoom < 20) Then
                intZoom = 20
            End If
            If (intZoom > 450000000.0F) Then
                intZoom = 450000000.0F
            End If
            objEscenario.Localizacion = New Coordenada(objEscenario.Localizacion.X, objEscenario.Localizacion.Y, intZoom)
        End If
        intMouseY = e.Y
        intMouseX = e.X
    End Sub


    Dim blnMouse As Boolean = False
    ''' <summary>
    ''' Evento para manejar la opcione del menu al dar click en la ventana
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub glcPantalla_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles glcPantalla.MouseDown
        If (e.Button = Windows.Forms.MouseButtons.Left) Then
            blnMouse = True
        End If
        'Info'
        If (tspInfo.Checked) Then
            Dim objConsulta As frmConsulta
            Dim objDataSet As DataSet = objEscenario.buscarInfo(e.X, e.Y)
            For Each objTabla As DataTable In objDataSet.Tables
                If (objTabla.Rows.Count > 0) Then
                    objConsulta = New frmConsulta()
                    objConsulta.Text = objTabla.TableName
                    objConsulta.dtgResultados.DataSource = objTabla
                    objConsulta.Show()
                End If
            Next
        End If
    End Sub

    Private Sub glcPantalla_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles glcPantalla.MouseUp
        blnMouse = False
    End Sub

    ''' <summary>
    ''' Evento para manejar el timer de pintado
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub trmPintar_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles trmPintar.Tick
        objEscenario.pintar()
        glcPantalla.Refresh()
    End Sub

    ''' <summary>
    ''' Evento para manejar la seleccion del color de fondo
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tspColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspColor.Click
        If (cldColores.ShowDialog = Windows.Forms.DialogResult.OK) Then
            objEscenario.Coloreado = New Colores(cldColores.Color)
        End If
    End Sub


    ''' <summary>
    ''' Evento para manejar las comunicaciones de sistogeo
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub bkwIniciar_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bkwIniciar.DoWork
        Try
            Dim objCommunicador As Ice.Communicator = Ice.Util.initialize(New String() {})
            Dim objAdaptador As Ice.ObjectAdapter = objCommunicador.createObjectAdapterWithEndpoints("CommunicationSistogeo", "tcp -p 10002")
            objAdaptador.add(New Comunicacion(), objCommunicador.stringToIdentity("CommunicationSistogeo"))
            objAdaptador.activate()
            objCommunicador.waitForShutdown()
            objCommunicador.destroy()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub


    ''' <summary>
    ''' Evento para manejar la opcione del menu que inicia el servidor de mapas
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tspInicio_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspInicio.Click
        tspInicio.Checked = Not tspInicio.Checked
        trmPintar.Enabled = Not trmPintar.Enabled
        trmMapa.Enabled = Not trmMapa.Enabled
        Try
            If (tspInicio.Checked) Then
                cargarDatos()
                bkwIniciar.RunWorkerAsync()
            Else
                bkwIniciar.CancelAsync()
            End If
        Catch ex As Exception
        End Try
    End Sub


    '========================================
    'Ejemplo de carga con codigo quemado
    '========================================
    'Sub cargarDatos()
    '    objEscenario.objLocalizacion = New Coordenada(1155019.0F, 994641.188F, 10)
    '    'objEscenario.objLocalizacion = New Coordenada(0.0F, 0.0F, 2)
    '    Conexion.CADENA_CONEXION = "dsn=quindiomsql64"
    '    Conexion.conectar()
    '    'JS: Texto de Prueba
    '    FuenteStroke.inicializarTextos()
    '    Dim objTexto As New FuenteStroke("unid", New Coordenada(objEscenario.objLocalizacion.X, objEscenario.objLocalizacion.Y), 1, 1)
    '    objTexto.Visible = True
    '    objTexto.Grosor = 1
    '    objTexto.Coloreado = New Colores(100, 100, 230)
    '    objTexto.Cadena = "objTexo juan antonio sanjuan"
    '    objTexto.Rotacion = 30
    '    'JS: Clientes
    '    Dim objClientes As CapaSQL = New CapaSQL("capaclientes", TIPO_ENTIDAD.Rectangulo, 200000, "SELECT CODE, XPOS, YPOS FROM CUSTMETR", objEscenario, TIPO_CAPA_SQL.ESTATICA, New Colores(200, 30, 30), 1.0F, 1.0F, 10000000, 0, "CUSTMETR")
    '    'Dim objClientes As CapaSQL = New CapaSQL("capaclientes", TIPO_ENTIDAD.Rectangulo, 200000, "SELECT CODE, XPOS, YPOS FROM CUSTMETR limit 500", objEscenario, TIPO_CAPA_SQL.ESTATICA, New Colores(200, 30, 30), 1.0F, 1.0F, 10000000, 0, "CUSTMETR")
    '    'JS: Lineas media
    '    Dim objLineasMedia As CapaSQL = New CapaSQL("lineasmedia", TIPO_ENTIDAD.Linea, 200000, "SELECT CODE, XPOS1, YPOS1, XPOS2, YPOS2, R, G, B FROM MVLINSEC", objEscenario, TIPO_CAPA_SQL.ESTATICA, Nothing, 2.0F, 2.0F, 10000000, 0, "MVLINSEC")
    '    'JS: Lineas de baja
    '    Dim objLineasBaja As CapaSQL = New CapaSQL("lineasbaja", TIPO_ENTIDAD.Linea, 200000, "SELECT CODE, XPOS1, YPOS1, XPOS2, YPOS2, R, G, B FROM LVLINSEC", objEscenario, TIPO_CAPA_SQL.ESTATICA, Nothing, 1.0F, 1.0F, 10000000, 0, "LVLINSEC")
    '    'JS: Transformadores
    '    Dim objTransformadores As CapaSQL = New CapaSQL("transformadores", TIPO_ENTIDAD.Triangulo, 200000, "SELECT CODE, XPOS, YPOS, R, G, B FROM TRANSFOR", objEscenario, TIPO_CAPA_SQL.ESTATICA, Nothing, 4.0F, 4.0F, 10000000, 0, "TRANSFOR")
    '    'JS: Adiciona los datos
    '    objEscenario.adicionar(objTexto)
    '    objEscenario.adicionar(objClientes)
    '    objEscenario.adicionar(objLineasMedia)
    '    objEscenario.adicionar(objLineasBaja)
    '    objEscenario.adicionar(objTransformadores)
    '    tspSelect.Checked = True
    '    trmPintar.Enabled = True
    'End Sub

    Private objDatosMapaIniciales As DatosMapa
    Sub cargarDatos()
        Dim objConfiguracion As Configuracion = cargarConfiguracion(Nothing)
        'Datos de Mapa Iniciales
        objDatosMapaIniciales = New DatosMapa
        objDatosMapaIniciales.Largo = 1
        objDatosMapaIniciales.Alto = 1
        objDatosMapaIniciales.x = objConfiguracion.XInicial
        objDatosMapaIniciales.y = objConfiguracion.YInicial
        objDatosMapaIniciales.z = objConfiguracion.ZInicial


        objEscenario.objLocalizacion = New Coordenada(objConfiguracion.XInicial, objConfiguracion.YInicial, objConfiguracion.ZInicial)
        Conexion.CADENA_CONEXION = objConfiguracion.CadenaConexion
        Conexion.conectar()
        'JS: Capa Cartografica
        If (Not objConfiguracion.Cartografia.Trim = "") Then
            Dim objCapaDXF As CapaDXF = New CapaDXF(objConfiguracion.Cartografia, 1000000, "DXF" & idCapaDxfActual, objEscenario, objConfiguracion.ColorCartografia, 1, 1, New Colores(120, 120, 120))
            objEscenario.adicionar(objCapaDXF)
        End If
        'JS:Capas Topologicas
        Dim objTabla As DataTable = objConfiguracion.CapaSQLTabla
        'JS: Carga las Capas SQL
        Dim objCapasSQL As CapaSQL = Nothing
        Dim objColorCapa As Colores = Nothing
        For Each objRegistro As DataRow In objTabla.Rows
            If (objRegistro("SQL").ToString().IndexOf("R, G, B") > 0) Then
                objColorCapa = Nothing
            Else
                objColorCapa = CType(objRegistro("Color"), Colores)
            End If
            objCapasSQL = New CapaSQL(objRegistro("Nombre").ToString, objConfiguracion.getTipoEntidad(objRegistro), 200000, objRegistro("SQL"), _
                                      objEscenario, TIPO_CAPA_SQL.ESTATICA, objColorCapa, Single.Parse(objRegistro("Tamano").ToString),
                                      Single.Parse(objRegistro("Tamano").ToString), 10000000, 0, objRegistro("Nombre").ToString)
            'JS: Adiciona los datos
            objEscenario.adicionar(objCapasSQL)
        Next
        tspSelect.Checked = True
        trmPintar.Enabled = True
    End Sub


    Public Shared Function devolverMapa() As String
        SyncLock objBloqueo
            strMapaRetorno = "nuevo"
        End SyncLock
        While (True)
            SyncLock objBloqueo
                If (Not strMapaRetorno.Equals("nuevo")) Then
                    Return strMapaRetorno
                    Exit While
                End If
            End SyncLock
        End While
        Return ""
    End Function

    Public Shared Function GetEncoderInfo(ByVal format As Imaging.ImageFormat) As Imaging.ImageCodecInfo
        Dim j As Integer
        Dim encoders() As Imaging.ImageCodecInfo
        encoders = Imaging.ImageCodecInfo.GetImageEncoders()
        j = 0
        While j < encoders.Length
            If encoders(j).FormatID = format.Guid Then
                Return encoders(j)
            End If
            j += 1
        End While
        Return Nothing
    End Function

    Private Sub trmMapa_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles trmMapa.Tick
        SyncLock objBloqueo
            If (strMapaRetorno.Equals("nuevo")) Then
                Dim objLocICE As Coordenada = objDatosMapa.Localizacion()
                objEscenario.Localizacion = New Coordenada(objLocICE.X, objLocICE.Y, objLocICE.Z)
                glcPantalla.MakeCurrent()
                Me.Width = objDatosMapa.Largo
                Me.Height = objDatosMapa.Alto
                objEscenario.pintar()
                glcPantalla.Refresh()
                Dim intLargo As Integer = CType(objDatosMapa.Largo, Integer)
                Dim intAlto As Integer = CType(objDatosMapa.Alto, Integer)
                Dim b As Bitmap = New Bitmap(intLargo, intAlto)
                Dim bmpData As Imaging.BitmapData = b.LockBits(New Rectangle(0, 0, intLargo, intAlto), Imaging.ImageLockMode.WriteOnly, Imaging.PixelFormat.Format24bppRgb)
                GL.Finish()
                GL.ReadPixels(0, 0, intLargo, intAlto, PixelFormat.Bgr, PixelType.UnsignedByte, bmpData.Scan0)
                b.UnlockBits(bmpData)
                b.RotateFlip(RotateFlipType.RotateNoneFlipY)
                Dim srd As New Random
                Dim ticks As String = srd.Next(100000000, 999999999)
                Dim strRuta As String = "C:\sistogeoimg\" & ticks & ".jpg"
                'b.Save(strRuta)
                Dim ic As Imaging.ImageCodecInfo = GetEncoderInfo(Imaging.ImageFormat.Jpeg)
                Dim ec As New Imaging.EncoderParameters(2)
                ec.Param(0) = New Imaging.EncoderParameter(Imaging.Encoder.Compression, Fix(Imaging.EncoderValue.RenderProgressive))
                ec.Param(0).Encoder = Imaging.Encoder.Compression
                ec.Param(1) = New Imaging.EncoderParameter(Imaging.Encoder.Quality, 100)
                ec.Param(1).Encoder = Imaging.Encoder.Quality
                b.Save(strRuta, ic, ec)
                strMapaRetorno = ticks
            End If
        End SyncLock
    End Sub

    Public idCapaDxfActual As Integer = 0

    Private Sub tspConfiguración_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspConfiguración.Click
        Dim objFrmConfiguracion As New frmConfigurarArea
        objFrmConfiguracion.ShowDialog(Me)
    End Sub

  
 
    Private Sub tspVerAreaCompleta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tspVerAreaCompleta.Click
        Try
            objEscenario.objLocalizacion = New Coordenada(objDatosMapaIniciales.x, objDatosMapaIniciales.y, objDatosMapaIniciales.z)
        Catch ex As Exception
        End Try
    End Sub
End Class
